import React from 'react';
import {connect} from 'react-redux'
import {Button, message, Form, Input, Switch, Modal, Select, Radio, Icon} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const {TextArea} = Input;
const RadioGroup = Radio.Group;
import {checkMenuDisabled, messages} from "share/common";
import CustomerInfoMaintenanceService from 'containers/customer-info-maintenance/customer-info-maintenance.service'
import moment from "moment";
import ListSelector from "components/list-selector";
import supplierService from 'containers/supplier-maintenance/supplier-management.service';
import vendorService from "./supplier-management.service";
import debounce from "lodash.debounce";

let deepRecord = {
  enabled: true,
  customerId: "",
  account: "",
  ownerName: null,
  accountMark: "02",
  primaryFlag: false,
  country: "",
  remark: "",
  status: '1001'
};
class NewAliAccount extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      confirmLoading: false,
      record: JSON.parse(JSON.stringify(deepRecord)),
      languageKey: 0,
      showListSelector: false,
      symbols: [],
    }
    this.onOk = debounce(this.onOk, 100)
  }


  componentWillMount() {
    this.getSymbols();
    let {record} = this.props.params;
    if(record && record.id) {
      this.setState({
        record,
      });
    }
  }

  getSymbols = () => {
    CustomerInfoMaintenanceService.getSymbols()
      .then(res => {
          this.setState({
            symbols: res.data,
          });
        }
      ).catch(err => {

    })
  };

  onOk = (e) => {
    const {record} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({loading: true});
        let method = null, param = Object.assign(record, values);
        param.vendorInfoId = this.props.params.vendorId;
        param.status = values.enabled ? '1001' : '1002';
        if (record.id) {
          //编辑
          method = supplierService.editAliPay(param)
        } else {
          method = supplierService.addAliPay(param)
        }
        method.then(response => {
          if (response.data.constraintFlag === 'false') {
            let title =
              <span>
                  {messages('basic-7.key1')/*供应商*/}<span style={{color: '#2292dd'}}>
                  {response.data.venInfoName}</span>{messages('basic-7.key2')/*下已有启用的*/}
                <span style={{color: '#2292dd'}}>{response.data.mesBankName}</span>
                {messages('basic-7.key3')/*主账户*/}
                <span style={{color: '#2292dd'}}>{response.data.mesVenBankNumberName}</span>
              </span>;
            let content =
              <span>{messages('basic-7.key4')/*点击【继续】，自动将主账户*/}
                <span style={{color: '#2292dd'}}>{response.data.mesVenBankNumberName}</span>
                {messages('basic-7.key5')/*设置为非主账户*/}
                </span>;
            let that = this;
            Modal.confirm({
              title: title,
              content: content,
              okText: messages('basic-7.key6')/*继续*/,
              onOk: () => {
                that.handleNotification(response.data)
              },
              onCancel: () => {
                that.setState({loading: false});
              }
            });
          } else {
            if (response.data.code !== '4080') {
              if (typeof record.id === 'undefined') {
                message.success(messages('basic-7.key7')/*保存成功！*/);
              } else {
                message.success(`${messages('common.operate.success')/*操作成功*/}`);
              }
              this.props.form.resetFields();
              this.setState({
                loading: false,
                isEnabled: true,
                isMainAccount: true
              });
              this.props.close(true);
            } else {
              message.error(`${messages('common.save.filed')/*保存失败*/},${response.data.msg}`);
              this.setState({loading: false});
              return;
            }
          }
        }).catch(e => {
          this.setState({loading: false});
        });
      }
    })
  };

  handleNotification = (values) => {
    const {record} = this.state;
    values.constraintFlag = 'go';
    let method = null;
    if (typeof record.id !== 'undefined') {
      values.id = record.id;
      method = supplierService.editAliPay(values)
    } else {
      method = supplierService.addAliPay(values)
    }
    method.then(response => {
      if (response.data.code !== '4080') {
        this.props.form.resetFields();
        this.setState({loading: false});
        this.props.close(true);
      } else {
        message.error(`${messages('common.save.filed')/*保存失败*/}, ${response.data.msg}`);
        this.setState({loading: false});
      }
    }).catch(e => {
      this.setState({loading: false});
    })
  };

  addBankAccount = (params) => {
    this.setState({
      confirmLoading: true,
    });
    supplierService.addAliPay(params)
      .then(res => {

          this.setState({
            confirmLoading: false,
          });
        }
      ).catch(err => {
      this.setState({
        confirmLoading: false,
      });
    })
  };

  editBankAccount = (params) => {
    this.setState({
      confirmLoading: true,
    });
    supplierService.editAliPay(params)
      .then(res => {
          this.props.close();
          this.setState({
            confirmLoading: false,
          });
        }
      ).catch(err => {
      this.setState({
        confirmLoading: false,
      });
    })
  };

  onCancel = () => {
    this.props.close();
  };

  //选择银行
  handleChangeBank = (result) => {
    const {record} = this.state;
    if(result.result.length) {
      record.country = result.result[0].name;
      this.setState({
        record,
      });
    }
    this.setState({
      showListSelector: false,
    });
  };

  changeListSelector = (e, bool) => {
    const {record} = this.state;
    if(record.id){
      return
    }
    this.setState({
      showListSelector: bool,
    });
  };
  render() {
    const {record, confirmLoading, languageKey, showListSelector, symbols, loading} = this.state;
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 16}
    };
    let disabled = checkMenuDisabled();
    let {noPermission} = this.props.params;
    return (
      <div>
        <Form className="new-form">
          <FormItem label={messages('common.column.status')/*状态*/}{...formItemLayout}>
            {getFieldDecorator('enabled', {
              valuePropName: "checked",
              initialValue: record.status == '1001',
            })(
              <Switch/>
            )}
          </FormItem>
          <FormItem label={messages('basic-7.key3')/*主账户*/}{...formItemLayout}>
            {getFieldDecorator('primaryFlag', {
              initialValue: record.primaryFlag,
            })(
              <RadioGroup>
                <Radio value={true}>{messages('common.yes')/*是*/}</Radio>
                <Radio value={false}>{messages('common.no')/*否*/}</Radio>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('basic-7.key8')/*账号来源*/}>
            {getFieldDecorator('accountType', {
              initialValue: 'ALIPAY_LOGON_ID',
              rules: [{
                required: true,
                message: messages('common.please.input')/*请输入*/
              }]
            })(
              <Select placeholder={messages('common.please.input')/*请输入*/} disabled>
                <Option key='BANKCARD_ACCOUNT' value='BANKCARD_ACCOUNT'>{messages('basic-7.key9')/*银行*/}</Option>
                <Option key='ALIPAY_LOGON_ID' value='ALIPAY_LOGON_ID'>{messages('basic-7.key10')/*支付宝*/}</Option>
              </Select>
            )}
            <div className="standard-note-text">
              {messages('basic-7.key11')/*保存后将不可修改*/}
            </div>
          </FormItem>
          <FormItem label={messages('basic-7.key12')/*持有人姓名*/} {...formItemLayout}>
            {getFieldDecorator('ownerName', {
              initialValue: record.ownerName,
              rules: [{
                required: true,
                message: messages('common.please.input')/*请输入*/
              },
                {
                  max: 256,
                  message: messages('basic-7.key13')/*最多输入256个字符*/
                },
              ]
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/} disabled={!!record.id}/>
            )}
            <div className="standard-note-text">
              {messages('basic-7.key11')/*保存后将不可修改*/}
            </div>
          </FormItem>
          <FormItem label={messages('basic-7.key14')/*支付宝账号*/} {...formItemLayout}>
            {getFieldDecorator('account', {
              initialValue: record.account,
              rules: [
                {
                  required: true,
                  message: messages('common.please.input')/*请输入*/
                },
                {
                  max: 64,
                  message: messages('basic-7.key15')/*最多输入64个字符*/
                },
              ]
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/} disabled={!!record.id}/>
            )}
            <div className="standard-note-text">
              {messages('basic-7.key11')/*保存后将不可修改*/}
            </div>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('basic-7.key16')/*账户标志*/}>
            {getFieldDecorator('accountMark', {
              initialValue: record.accountMark || "02",
            })(
              <Select placeholder={messages('common.please.input')/*请输入*/}>
                {
                  symbols.map(item => {
                    return(
                      <Option key={item.value} value={item.value}>{item.messageKey}</Option>
                    )
                  })
                }
              </Select>
            )}
            <div className="standard-note-text">{messages('basic-7.key17')/*个人身份信息开户为对私，公司资质开户为对公，银企直联必需字段*/}</div>
          </FormItem>
          <FormItem label={messages('basic-7.key18')/*国家*/}
                    {...formItemLayout}>
            <div style={{width: "66%"}}
                 onClick={(e) =>this.changeListSelector(e,true)}
                 className="real-input-fake-select">
              <Input placeholder={messages('common.select')/*请选择*/}
                     value={record.country}
                     suffix={<Icon type="down" style={{fontSize: 12}}/>}
                     onChange={()=>{}}
                     disabled={!!record.id}
                     key={languageKey}/>
            </div>
            <div className="standard-note-text">
              {messages('basic-7.key11')/*保存后将不可修改*/}
            </div>
          </FormItem>
          <FormItem label={messages('common.remark')/*备注*/} {...formItemLayout}>
            {getFieldDecorator('remark', {
              initialValue: record.remark,
            })(
              <TextArea placeholder={messages('common.please.input')/*请输入*/}/>
            )}
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" onClick={this.onOk} loading={loading} disabled={disabled || noPermission}>
              {messages('common.save')/*保存*/}
            </Button>
            <Button onClick={this.onCancel}>
              {messages('common.cancel')/*取消*/}
            </Button>
          </div>
        </Form>
        <ListSelector
          visible={showListSelector}
          type="select_country"
          selectedData={[]}
          onOk={this.handleChangeBank}
          onCancel={(e) =>this.changeListSelector(e,false)}
          single
        />
      </div>
    )
  }
}


NewAliAccount.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    authPolicyAll: state.main.authPolicyAll,
  }
}

const wrappedNewAliAccount = Form.create()(NewAliAccount);
export default connect(mapStateToProps)(wrappedNewAliAccount);
